package com.example.lottery.controller;

import com.example.lottery.common.errorcode.ControllerErrorCodeConstants;
import com.example.lottery.common.exception.ControllerException;
import com.example.lottery.common.pojo.CommonResult;
import com.example.lottery.common.utils.JWTUtil;
import com.example.lottery.common.utils.JacksonUtil;
import com.example.lottery.controller.param.UserLoginByMessageParam;
import com.example.lottery.controller.param.UserLoginByPasswordParam;
import com.example.lottery.controller.param.UserRegisterParam;
import com.example.lottery.controller.result.UserBaseInfoResult;
import com.example.lottery.controller.result.UserLoginResult;
import com.example.lottery.controller.result.UserRegisterResult;
import com.example.lottery.service.IUserService;
import com.example.lottery.service.IVerificationCodeService;
import com.example.lottery.service.dto.UserBaseInfoDTO;
import com.example.lottery.service.dto.UserLoginDTO;
import com.example.lottery.service.dto.UserRegisterDTO;
import com.example.lottery.service.enums.UserIdentityEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IVerificationCodeService verificationCodeService;

    @PostMapping("/register")
    public CommonResult<UserRegisterResult> UserRegister(@RequestBody @Validated UserRegisterParam userRegisterParam){
        log.info("UserRegister  UserRegisterParam：{}", JacksonUtil.writeValueAsString(userRegisterParam));
        UserRegisterDTO userRegisterDTO = userService.userRegister(userRegisterParam);
        log.info("注册成功！");
        return CommonResult.success(convertToUserRegisterResult(userRegisterDTO));
    }

    private UserRegisterResult convertToUserRegisterResult(UserRegisterDTO userRegisterDTO) {
        UserRegisterResult userRegisterResult=new UserRegisterResult();
        //校验参数
        if(userRegisterDTO==null){
            //打印日志
            log.warn(ControllerErrorCodeConstants.REGISTER_ERROR.getMsg());
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        //赋值
        userRegisterResult.setUserId(userRegisterDTO.getUserId());
        return userRegisterResult;
    }

    @GetMapping("/verification-code/send")
    public void sendVerificationCode(@RequestParam(value = "phoneNumber",required = false) String phoneNumber
            , HttpServletResponse response){
        log.info("sendVerificationCode  phoneNumber：{}",phoneNumber);
        verificationCodeService.sendVerificationCode(response,phoneNumber);
    }

    @PostMapping("/password/login")
    public CommonResult<UserLoginResult> userLoginByPassword(@Validated @RequestBody UserLoginByPasswordParam userLoginByPasswordParam){
        log.info("UserLoginByPasswordResult  userLoginByPassword：{}",userLoginByPasswordParam);
        UserLoginDTO userLoginDTO = userService.userLogin(userLoginByPasswordParam);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }

    @PostMapping("/message/login")
    public CommonResult<UserLoginResult> userLoginByMessage(@Validated @RequestBody UserLoginByMessageParam userLoginByMessageParam){
        log.info("userLoginByMessage  userLoginByMessageParam：{}",userLoginByMessageParam);
        UserLoginDTO userLoginDTO = userService.userLogin(userLoginByMessageParam);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }

    @GetMapping("/base-user/find-list")
    public CommonResult<List<UserBaseInfoResult>> findUserBaseInfo(String identity){
        //1-    判断identity是否存在于枚举类
        UserIdentityEnum userIdentityEnum = UserIdentityEnum.forName(identity);
        if(userIdentityEnum==null&&identity!=null){
                //说明不是ADMIN 或 NORMAL
                log.warn("用户身份非法");
                throw new ControllerException(ControllerErrorCodeConstants.USER_IDENTITY_ENUM_ERROR);
        }
        //2-    根据identity获取用户列表：为空显示全部用户
        List<UserBaseInfoDTO> userBaseInfoDTOs=userService.findUserBase(UserIdentityEnum.forName(identity));
        //3-    类型转换 DTO->RESULT
        return CommonResult.success(convertToUserBaseInfoResultList(userBaseInfoDTOs));
    }

    /**
     * 退出接口
     * @return
     */
    @GetMapping("/exit")
    public CommonResult exitUser(HttpServletRequest request){
        String user_token = request.getHeader("user_token");
        userService.exit(user_token);
        return CommonResult.success(null);
    }

    private List<UserBaseInfoResult> convertToUserBaseInfoResultList(List<UserBaseInfoDTO> userBaseInfoDTOs) {
        if(userBaseInfoDTOs==null){
            log.info(ControllerErrorCodeConstants.USER_LIST_ERROR.getMsg());
            throw new ControllerException(ControllerErrorCodeConstants.USER_LIST_ERROR);
        }
        //-    开始映射并返回值
        return userBaseInfoDTOs.stream()
                .map(userBaseInfoDTO -> {
                    UserBaseInfoResult userBaseInfoResult=new UserBaseInfoResult();
                    userBaseInfoResult.setUserId(userBaseInfoDTO.getId());
                    userBaseInfoResult.setUserName(userBaseInfoDTO.getUserName());
                    userBaseInfoResult.setIdentity(userBaseInfoDTO.getIdentity().name());
                    return userBaseInfoResult;
                }).collect(Collectors.toList());
    }

    private UserLoginResult convertToUserLoginResult(UserLoginDTO userLoginDTO) {
        UserLoginResult userLoginResult =new UserLoginResult();
        if(userLoginDTO ==null){
            log.info(ControllerErrorCodeConstants.LOGIN_ERROR.getMsg());
            throw new ControllerException(ControllerErrorCodeConstants.LOGIN_ERROR);
        }
        userLoginResult.setToken(userLoginDTO.getToken());
        userLoginResult.setIdentity(userLoginDTO.getIdentity().name());
        return userLoginResult;
    }

}
